#  Copyright 2009-2010 Michal Trzcinka
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
# 
#  http://www.apache.org/licenses/LICENSE-2.0
# 
#  Unless required by applicable law or agreed to in writing, software distributed
#  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
#  CONDITIONS OF ANY KIND, either express or implied. See the License for the
#  specific language governing permissions and limitations under the License.

if $0 != 'irb' #don't want to run it in console

  require 'rufus/scheduler'
  scheduler = Rufus::Scheduler.start_new
  
  scheduler.every("1m") do
    puts "[SCHEDULER] Executing scheduled tasks..."
    start = Time.now

    #Destroying all grid events that weren't received
    unreceived_events = GridEvent.delete_all(["created_at < ?", 10.minutes.ago])
    puts "[SCHEDULER] Removed #{unreceived_events} unreceived events"

    #Destroying all stale sessions and logging out corresponding users
    stale_sessions = ActiveRecord::SessionStore::Session.delete_all(['updated_at < ?', 30.minutes.ago.utc])
    puts "[SCHEDULER] Removed #{stale_sessions} stale sessions"
    
    puts "[SCHEDULER] Scheduled task completed in #{Time.now - start} s"
  end  
  
end

